package com.example.larouzey.showweb;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity{
    private EditText ed;
    private TextView tv;
    private Button bt;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    ByteArrayOutputStream baos=(ByteArrayOutputStream) msg.obj;
                    tv.setText(baos.toString());
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ed=(EditText)findViewById(R.id.editText);
        tv=(TextView)findViewById(R.id.textView);
        bt=(Button)findViewById(R.id.button);

        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String string;
                string = ed.getText().toString();
                new Thread() {
                    public void run() {
                    try {
                            URL url = new URL(string);
                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                            InputStream is = connection.getInputStream();
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            byte[] data = new byte[1024];
                            while (is.read(data) != -1)
                            {
                                baos.write(data);
                            }
                            Message msg = new Message();
                            msg.what = 1;
                            msg.obj = baos;
                            handler.sendMessage(msg);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        }
                    }.start();
            }
        });
    }
}
